package com.ss.android.download;

import static com.ss.android.video.SSMediaPlayerWrapper.CALLBACK_ON_COMPLETE;
import static com.ss.android.video.SSMediaPlayerWrapper.CALLBACK_ON_ERROR;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.os.PowerManager;
import android.os.Process;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;

import com.bytedance.common.utility.io.NetHackDbg;
import com.ss.android.download.DownloadInfo.NetworkState;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collections;
import java.util.Iterator;

public final class n implements Runnable {
    final class a {
        public String a;
        public String b;
        public int c;
        public boolean d;
        public String e;
        public long f;
        public long g;
        public String h;
        public boolean i;
        public long j;
        public long k;
        public int l;
        public long m;
        public long n;
        public long o;
        public long p;
        public String q;
        public String r;
        public int s;
        public URL t;

        public a(DownloadInfo arg7) {

            this.c = 0;
            this.d = false;
            this.f = -1;
            this.g = 0;
            this.i = false;
            this.j = 0;
            this.k = 0;
            this.l = -1;
            this.p = -1;
            this.b = arg7.f;
            this.e = arg7.b;
            this.a = arg7.e;
            this.f = arg7.r;
            this.g = arg7.s;
        }
    }

    private final Context a;
    private final DownloadInfo b;
    private final t c;
    private final r d;
    private final g e;
    private volatile boolean f;

    public n(Context arg1, t arg2, DownloadInfo arg3, r arg4, g arg5) {

        this.a = arg1;
        this.c = arg2;
        this.b = arg3;
        this.d = arg4;
        this.e = arg5;
    }

    private int a(a arg8, byte[] arg9, InputStream arg10) throws StopRequestException {
        int v0_1;
        String v6 = null;
        try {
            v0_1 = arg10.read(arg9);
        } catch (IOException v0) {
            if ("unexpected end of stream".equals(v0.getMessage())) {
                return -1;
            }

            ContentValues v1 = new ContentValues();
            v1.put("current_bytes", Long.valueOf(arg8.g));
            k.a(this.a).a(this.b.b(), v1, v6, null);
            if (this.b(arg8)) {
                throw new StopRequestException(489, "Failed reading response: " + v0 + "; unable to resume", ((Throwable) v0));
            }

            throw new StopRequestException(495, "Failed reading response: " + v0, ((Throwable) v0));
        }

        return v0_1;
    }

    private static long a(URLConnection arg2, String arg3) {
        long v0_1;
        try {
            v0_1 = Long.parseLong(arg2.getHeaderField(arg3));
        } catch (NumberFormatException v0) {
            v0_1 = -1;
        }

        return v0_1;
    }

    private void a() throws StopRequestException {
        int v0 = 196;
        this.f = false;
        NetworkState v2 = this.b.a();
        if (v2 != NetworkState.OK) {
            int v1 = 195;
            if (v2 == NetworkState.UNUSABLE_DUE_TO_SIZE) {
                this.b.a(true);
            } else if (v2 == NetworkState.RECOMMENDED_UNUSABLE_DUE_TO_SIZE) {
                this.b.a(false);
            } else {
                v0 = v1;
            }

            throw new StopRequestException(v0, v2.name());
        }
    }

    private void a(a arg15) throws StopRequestException {
        URLConnection v11 = null;
        int v2_1;
        long v12 = -1;
        int v10 = 489;
        String v3 = null;
        arg15.p = v12;
        arg15.q = v3;
        arg15.r = v3;
        arg15.s = 0;
        if (!TextUtils.isEmpty(arg15.a)) {
            if (com.ss.android.download.aa.c) {
                Log.i("SsDownloadManager", "have run thread before for id: " + this.b.a + ", and state.mFilename: " + arg15.a);
            }

            if (!o.a(arg15.a, this.d.b)) {
                throw new StopRequestException(492, "found invalid internal destination filename");
            }

            File v2 = new File(arg15.a);
            if (!v2.exists()) {
//                goto label_85;
            } else {
                if (com.ss.android.download.aa.c) {
                    Log.i("SsDownloadManager", "resuming download for id: " + this.b.a + ", and state.mFilename: " + arg15.a);
                }

                long v6 = v2.length();
                if (v6 == 0) {
                    if (com.ss.android.download.aa.d) {
                        Log.d("SsDownloadManager", "setupDestinationFile() found fileLength=0, deleting " + arg15.a);
                    }

                    v2.delete();
                    arg15.a = v3;
                    if (!com.ss.android.download.aa.c) {
//                    goto label_85;
                    } else {
                        Log.i("SsDownloadManager", "resuming download for id: " + this.b.a + ", BUT starting from scratch again: ");
//                    goto label_85;
                    }
                } else {

                    if (this.b.t == null && !this.b.c) {
                        if (com.ss.android.download.aa.d) {
                            Log.d("SsDownloadManager", "setupDestinationFile() unable to resume download, deleting " + arg15.a);
                        }
                        v2.delete();
                        throw new StopRequestException(v10, "Trying to resume a download that can\'t be resumed");
                    }

                    if (com.ss.android.download.aa.c) {
                        Log.i("SsDownloadManager", "resuming download for id: " + this.b.a + ", and starting with file of length: " + v6);
                    }

                    arg15.g = ((long) (((int) v6)));
                    if (this.b.r != v12) {
                        arg15.p = this.b.r;
                    }

                    arg15.h = this.b.t;
                    arg15.i = true;
                    if (!com.ss.android.download.aa.c) {
//                goto label_85;
                    } else {
                        Log.i("SsDownloadManager", "resuming download for id: " + this.b.a + ", state.mCurrentBytes: " + arg15.g + ", and setting mContinuingDownload to true: ");
                    }
                }
            }
        }

        label_85:
        if (arg15.g == arg15.f) {
            Log.i("SsDownloadManager", "Skipping initiating request for download " + this.b.a + "; already completed");
        } else {
            while (true) {
                v2_1 = arg15.s;
                arg15.s = v2_1 + 1;
                if (v2_1 < 5) {
                    try {
                        this.a();
                        v11 = arg15.t.openConnection();
                        ((HttpURLConnection) v11).setInstanceFollowRedirects(false);
                        ((HttpURLConnection) v11).setConnectTimeout(20000);
                        ((HttpURLConnection) v11).setReadTimeout(20000);
                        this.b(arg15, ((HttpURLConnection) v11));
                        v2_1 = ((HttpURLConnection) v11).getResponseCode();
                        switch (v2_1) {
                            case 200: {
                                if (arg15.i) {
                                    throw new StopRequestException(489, "Expected partial, but received OK");
                                }

                                arg15.q = ((HttpURLConnection) v11).getHeaderField("Content-Disposition");
                                arg15.r = ((HttpURLConnection) v11).getHeaderField("Content-Location");
                                if (arg15.b == null) {
                                    arg15.b = ((HttpURLConnection) v11).getContentType();
                                }
                                arg15.h = ((HttpURLConnection) v11).getHeaderField("ETag");
                                String v2_4 = ((HttpURLConnection) v11).getHeaderField("Transfer-Encoding");
                                if (v2_4 == null) {
                                    arg15.p = n.a(v11, "Content-Length");
                                } else {
                                    Log.i("SsDownloadManager", "Ignoring Content-Length since Transfer-Encoding is also defined");
                                    arg15.p = -1;
                                }

                                arg15.f = arg15.p;
                                this.b.r = arg15.p;
                                if (arg15.p == v12) {
                                    if (v2_4 != null && (v2_4.equalsIgnoreCase("chunked"))) {
                                        v2_1 = 0;
                                    } else {
                                        v2_1 = 1;
                                    }
                                } else {
                                    label_265:
                                    v2_1 = 0;
                                }

                                if (!this.b.c && v2_1 != 0) {
                                    throw new StopRequestException(489, "can\'t know size of download, giving up");
                                }

                                arg15.a = o.a(this.b.b, this.b.d, arg15.q, arg15.r, arg15.b, this.b.g, arg15.p, this.d);
                                ContentValues v2_5 = new ContentValues();
                                v2_5.put("_data", arg15.a);
                                if (arg15.h != null) {
                                    v2_5.put("etag", arg15.h);
                                }

                                if (arg15.b != null) {
                                    v2_5.put("mimetype", arg15.b);
                                }

                                v2_5.put("total_bytes", Long.valueOf(this.b.r));
                                k.a(this.a).a(this.b.b(), v2_5, null, null);
                                this.a();
                                this.a(arg15, ((HttpURLConnection) v11));
                                if (v11 == null) {
                                    return;
                                }
                                return;
                            }
                            case 206: {
                                if (!arg15.i) {
                                    throw new StopRequestException(489, "Expected OK, but received partial");
                                }
                                this.a(arg15, ((HttpURLConnection) v11));
                                if (v11 == null) {
                                    return;
                                }
                                return;
                            }
                            case 301:
                            case CALLBACK_ON_COMPLETE:
                            case CALLBACK_ON_ERROR:
                            case 307: {
                                arg15.t = new URL(arg15.t, ((HttpURLConnection) v11).getHeaderField("Location"));
                                if (v2_1 == 301) {
                                    arg15.e = arg15.t.toString();
                                }
                                if (v11 == null) {
                                    continue;
                                }
                                ((HttpURLConnection) v11).disconnect();
                                continue;
                            }
                            case 416: {
                                throw new StopRequestException(489, "Requested range not satisfiable");
                            }
                            case 500: {
                                throw new StopRequestException(500, ((HttpURLConnection) v11).getResponseMessage());
                            }
                            case 503: {
                                arg15.c = v11.getHeaderFieldInt("Retry-After", -1);
                                if (arg15.c < 0) {
                                    arg15.c = 0;
                                } else {
                                    if (arg15.c < 30) {
                                        arg15.c = 30;
                                    } else if (arg15.c > 86400) {
                                        arg15.c = 86400;
                                    }

                                    arg15.c += o.a.nextInt(31);
                                    arg15.c *= 1000;
                                }
                                throw new StopRequestException(503, ((HttpURLConnection) v11).getResponseMessage());
                            }
                        }

                        StopRequestException.throwUnhandledHttpError(v2_1, ((HttpURLConnection) v11).getResponseMessage());
                        if (v11 != null) {
                        } else {
                            continue;
                        }
                    } catch (IOException v2_3) {
                        throw new StopRequestException(495, v2_3);
                    } finally {
                        if (v11 != null) {
                            try {
                                ((HttpURLConnection) v11).disconnect();
                            } catch (Exception e) {

                            }
                        }
                    }
                } else {
                    throw new StopRequestException(497, "Too many redirects");
                }
            }
        }
    }

    private void a(a arg8, HttpURLConnection arg9) throws StopRequestException {
        FileOutputStream v2 = null;
        InputStream v4 = null;
        FileDescriptor v3 = null;
        try {
            try {
                v4 = arg9.getInputStream();
            } catch (IOException v1_1) {
                throw new StopRequestException(495, v1_1);
            }

            try {
                v2 = new FileOutputStream(arg8.a, true);
                v3 = v2.getFD();
            } catch (IOException v1_1) {
                throw new StopRequestException(492, v1_1);
            }

            this.a(arg8, v4, v2);
            try {
                if (v4 == null) {
                    v2.flush();
                    if (v3 != null) {
                        v3.sync();
                    }
                }
            } catch (Throwable tr) {

            }
        } finally {
            try {
                v2.close();
            } catch (Exception e) {

            }
            try {
                v4.close();
            } catch (Exception e) {

            }
        }
    }

    private static void a(a arg3, int arg4) {
        if (arg3.a != null && (com.ss.android.download.a.a.b(arg4))) {
            if (com.ss.android.download.aa.d) {
                Log.d("SsDownloadManager", "cleanupDestination() deleting " + arg3.a);
            }

            new File(arg3.a).delete();
            arg3.a = null;
        }
    }

    private void a(a arg7, int arg8, String arg9, int arg10) {
        String v4 = null;
        ContentValues v0 = new ContentValues();
        v0.put("status", Integer.valueOf(arg8));
        v0.put("_data", arg7.a);
        v0.put("mimetype", arg7.b);
        v0.put("lastmod", Long.valueOf(this.c.a()));
        v0.put("numfailed", Integer.valueOf(arg10));
        v0.put("method", Integer.valueOf(arg7.c));
        if (!TextUtils.equals(this.b.b, arg7.e)) {
            v0.put("uri", arg7.e);
        }

        if (!TextUtils.isEmpty(((CharSequence) arg9))) {
            v0.put("errorMsg", arg9);
        }

        k.a(this.a).a(this.b.b(), v0, v4, ((String[]) null));
        if (com.ss.android.download.a.a.c(arg8)) {
            DownloadInfo v0_1 = this.b;
            if (v0_1.n != null) {
                Intent v1 = new Intent("android.ss.intent.action.DOWNLOAD_COMPLETE");
                v1.setPackage(v0_1.n);
                v1.putExtra("extra_download_id", v0_1.a);
                v1.putExtra("extra_download_visibility", v0_1.h);
                v1.putExtra("status", arg8);
                v0_1.D.a(v1);
            }
        }
    }

    private void a(a arg11, InputStream arg12, OutputStream arg13) throws StopRequestException {
        DownloadInfo v1_2;
        byte[] v0 = new byte[4096];
        while (true) {
            int v1 = this.a(arg11, v0, arg12);
            if (v1 == -1) {
                break;
            }

            arg11.d = true;
            this.a(arg11, v0, v1, arg13);
            arg11.g += ((long) v1);
            long v2 = SystemClock.elapsedRealtime();
            long v4 = v2 - arg11.n;
            if (v4 > 500) {
                v4 = (arg11.g - arg11.o) * 1000 / v4;
                arg11.m = arg11.m == 0 ? v4 : (v4 + arg11.m * 3) / 4;
                if (arg11.n != 0) {
                    this.e.a(this.b.a, arg11.m);
                }

                arg11.n = v2;
                arg11.o = arg11.g;
            }

            if (arg11.g - arg11.j > 4096 && v2 - arg11.k > 1500) {
                ContentValues v1_1 = new ContentValues();
                v1_1.put("current_bytes", Long.valueOf(arg11.g));
                k.a(this.a).a(this.b.b(), v1_1, null, null);
                arg11.j = arg11.g;
                arg11.k = v2;
            }

            if (com.ss.android.download.aa.d) {
                Log.v("SsDownloadManager", "downloaded " + arg11.g + " for " + this.b.b);
            }

            v1_2 = this.b;
            synchronized (v1_2) {
                if (this.b.i == 1) {
                    throw new StopRequestException(193, "download paused by owner");
                }

                if (this.b.j != 490 && !this.b.v) {
                    continue;
                }
                throw new StopRequestException(490, "download canceled");
            }
        }

        ContentValues v0_2 = new ContentValues();
        v0_2.put("current_bytes", Long.valueOf(arg11.g));
        if (arg11.p == -1) {
            v0_2.put("total_bytes", Long.valueOf(arg11.g));
        }

        k.a(this.a).a(this.b.b(), v0_2, null, null);
        int v0_3 = arg11.p == -1 || arg11.g == arg11.p ? 0 : 1;
        if (v0_3 != 0) {
            if (this.b(arg11)) {
                throw new StopRequestException(489, "mismatched content length; unable to resume");
            }
            throw new StopRequestException(495, "closed socket before end of file");
        }

        return;
    }

    private void a(a aVar, byte[] bArr, int i, OutputStream outputStream) throws StopRequestException {
        boolean z = false;
        r rVar = this.d;
        int i2 = this.b.g;
        String str = aVar.a;
        long j = (long) i;
        if (rVar.a(j) >= 1048576) {
            rVar.a(i2, str, j);
        }
        while (true) {
            try {
                outputStream.write(bArr, 0, i);
                return;
            } catch (IOException e2) {
                if (!z) {
                    this.d.a(this.b.g, aVar.a, (long) i);
                    z = true;
                } else {
                    throw new StopRequestException(492, "Failed to write data: " + e2);
                }
            }
        }
    }


    private boolean b(a arg5) {
        boolean v0 = arg5.g <= 0 || (this.b.c) || arg5.h != null ? false : true;
        return v0;
    }

    @TargetApi(value = 5)
    private void b(a arg5, HttpURLConnection arg6) {
        Iterator v2 = Collections.unmodifiableList(this.b.B).iterator();
        while (v2.hasNext()) {
            Pair<String, String> v0 = (Pair<String, String>) v2.next();
            arg6.addRequestProperty(v0.first, v0.second);
        }

        if (arg6.getRequestProperty("User-Agent") == null) {
            String v1 = "User-Agent";
            String v0_1 = this.b.p;
            if (v0_1 == null) {
                v0_1 = com.ss.android.download.aa.b;
            }

            arg6.addRequestProperty(v1, v0_1);
        }

        arg6.setRequestProperty("Accept-Encoding", "identity");
        if (arg5.i) {
            if (arg5.h != null) {
                arg6.addRequestProperty("If-Match", arg5.h);
            }

            arg6.addRequestProperty("Range", "bytes=" + arg5.g + "-");
        }
    }

    @SuppressLint("InvalidWakeLockTag")
    public final void run() {
        int v0_5;
        PowerManager.WakeLock v4_1;
        int v1_1;
        PowerManager.WakeLock v1 = null;
        Object v0_1;
        a v7 = null;
        int v5 = 194;
        String v2 = null;
        int v4 = 491;
        int v3 = 200;
        Process.setThreadPriority(10);
        try {
            if (DownloadInfo.a(k.a(this.a), this.b.a) == v3) {
                Log.d("SsDownloadManager", "Download " + this.b.a + " already finished; skipping");
                return;
            }

            v7 = new a(this.b);
            v3 = this.b.k;
            v0_1 = this.a.getSystemService(Context.POWER_SERVICE);
            v1 = ((PowerManager) v0_1).newWakeLock(1, "SsDownloadManager");
            v1.acquire();
            Log.i("SsDownloadManager", "Download " + this.b.a + " starting");
            NetworkInfo v0_3 = this.c.b();
            if (v0_3 != null) {
                v7.l = v0_3.getType();
            }
            try {
                v7.t = new URL(v7.e);
            } catch (MalformedURLException v0_4) {
                throw new StopRequestException(400, v0_4);
            }
            this.a(v7);
            if (v7.a != null) {
                NetHackDbg.c(v7.a);
            }
            v0_5 = 200;
            n.a(v7, v0_5);
            this.a(v7, 200, null, v3);
            Log.i("SsDownloadManager", "Download " + this.b.a + " finished with status " + com.ss.android.download.a.a.d(200));
            if (v1 != null) {
                v1.release();
            }
            this.d.a();
            return;
        } catch (StopRequestException v0_2) {
            v2 = v0_2.getMessage();
            String v8 = "Aborting request for download " + this.b.a + ": " + v2;
            Log.w("SsDownloadManager", v8);
            if (com.ss.android.download.aa.c) {
                Log.w("SsDownloadManager", v8, v0_2);
            }
            v4 = v0_2.getFinalStatus();
            if (v4 != v5) {
//                        goto label_150;
            } else {
                throw new IllegalStateException("Execution should always throw final error codes");
            }
            switch (v4) {
                case 495:
                case 500:
                case 503: {
                    v0_5 = 1;
                    break;
                }
                default: {
                    v0_5 = 0;
                    break;
                }
            }

            if (v0_5 != 0) {
                if (v7.d) {
                    v3 = 1;
                } else {
                    ++v3;
                }

                if (v3 >= 5) {
//                                goto label_167;
                } else {
                    NetworkInfo v0_3 = this.c.b();
                    if (v0_3 != null && v0_3.getType() == v7.l && (v0_3.isConnected())) {
                        v4 = v5;
                    } else {
                        v4 = 195;
                    }
                }
            }
            n.a(v7, v4);
            this.a(v7, v4, v2, v3);
            Log.i("SsDownloadManager", "Download " + this.b.a + " finished with status " + com.ss.android.download.a.a.d(v4));
            if (v1 != null) {
                v1.release();
            }
            v1 = null;
            this.d.a();
            return;
        } catch (Throwable v0) {
            v2 = v0.getMessage();
            Log.w("SsDownloadManager", "Exception for id " + this.b.a + ": " + v2, v0);
            v0_5 = 491;
            n.a(v7, v0_5);
            this.a(v7, 491, v2, v3);
            Log.i("SsDownloadManager", "Download " + this.b.a + " finished with status " + com.ss.android.download.a.a.d(491));
            if (v1 != null) {
                v1.release();
            }
            v1 = null;
            this.d.a();
            return;
        } finally {
            this.e.a(this.b.a, 0);
        }
    }
}

